/**
 * 电路编辑器主入口 - 符合utility.mdr规则
 */
import { EditorCore } from './EditorCore.js';
import { CanvasManager } from './CanvasManager.js';
import { ToolbarManager } from './ToolbarManager.js';

export class CircuitEditor {
    private core: EditorCore;
    private canvas: CanvasManager;
    private toolbar: ToolbarManager;

    constructor(container: HTMLElement) {
        // 创建核心模块
        this.core = new EditorCore();
        
        // 初始化整个编辑器UI容器（添加边框）
        const editorContainer = document.createElement('div');
        editorContainer.className = 'circuit-editor-container';
        editorContainer.style.display = 'flex';
        editorContainer.style.flexDirection = 'column';
        editorContainer.style.gap = '0px'; // 移除间隙，使用padding
        editorContainer.style.border = '2px solid #ccc';
        editorContainer.style.borderRadius = '8px';
        editorContainer.style.backgroundColor = '#f8f9fa';
        editorContainer.style.overflow = 'hidden'; // 确保圆角正确显示
        container.appendChild(editorContainer);

        // 创建顶部工具栏区域（无边框）
        const toolbarContainer = document.createElement('div');
        toolbarContainer.className = 'toolbar-container';
        toolbarContainer.style.padding = '10px';
        toolbarContainer.style.borderBottom = '1px solid #e0e0e0'; // 轻微的分隔线
        editorContainer.appendChild(toolbarContainer);

        // 创建工具栏
        this.toolbar = new ToolbarManager(toolbarContainer);

        // 创建画布区域（无边框）
        const canvasContainer = document.createElement('div');
        canvasContainer.className = 'canvas-container';
        canvasContainer.style.padding = '10px';
        canvasContainer.style.flex = '1'; // 占据剩余空间
        editorContainer.appendChild(canvasContainer);

        // 创建画布
        this.canvas = new CanvasManager(canvasContainer);

        // 设置事件转发
        this.setupEventForwarding();
    }

    private setupEventForwarding(): void {
        window.addEventListener('circuit-editor:tool-selected', ((e: Event) => {
            const event = e as CustomEvent;
            this.core.setTool(event.detail.tool);
        }) as EventListener);

        window.addEventListener('circuit-editor:element-added', ((e: Event) => {
            // 不再重复添加元素，仅处理其他逻辑
            const event = e as CustomEvent;
            console.log('Element added event received:', event.detail.element);
        }) as EventListener);
    }
}